<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
  >
    <el-form
      ref="formRef"
      label-width="100px"
      :model="state.formData"
      :rules="state.formRules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色名称:" prop="roleName">
            <el-input
              v-model="state.formData.roleName"
              :maxlength="16"
              :show-word-limit="true"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色编码:" prop="roleCode">
            <el-input
              v-model="state.formData.roleCode"
              :maxlength="16"
              readonly
              :show-word-limit="true"
              type="text"
            >
              <template #append>
                <el-button icon="Refresh" @click="handleRoleNameChange">
                  编码
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色类别:" prop="roleTypeName">
            <el-input v-model="state.formData.roleTypeName" :readonly="true">
              <template #append>
                <el-button icon="Search" @click="openRoleTypeSelector" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序号:" prop="orderId">
            <el-input v-model="state.formData.orderId" type="number" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="state.formData.remark"
              :maxlength="128"
              rows="4"
              :show-word-limit="true"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button icon="circle-close" type="warning" @click="close">
        取消
      </el-button>
      <el-button icon="circle-check" type="primary" @click="save">
        确定
      </el-button>
    </template>
    <TreeNodePicker
      ref="roleTypeRef"
      title="选择角色类别"
      @change="handleRoleTypeSelect"
    />
  </el-dialog>
</template>

<script setup name="RoleEdit">
import { useMessage } from "@/hooks/message";
import { addRole, updateRole, queryValid } from "@/api/admin/org/role/";
import TreeNodePicker from "@/components/treeNodePicker.vue";
import pinyin from "js-pinyin";

const props = defineProps({
  title: {
    type: String,
    default: "角色"
  },
  width: {
    type: String,
    default: "40%"
  },
  model: {
    type: Boolean,
    default: true
  }
});
const emits = defineEmits(["confirm"]);

const formRef = ref(null);
const roleTypeRef = ref(null);

const state = reactive({
  operationAdd: false,
  formData: {
    id: "",
    roleCode: "",
    roleName: "",
    orderId: 0,
    roleTypeCode: "",
    roleTypeName: "",
    remark: ""
  },
  dialogTitle: props.title,
  formRules: {
    roleCode: [
      { required: true, message: "角色编码不能为空", trigger: "blur" },
      {
        validator: async (rule, value, callback) => {
          const res = await queryValid(state.formData);
          if (res.code != 200) {
            callback(new Error(res.msg));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    roleName: [
      { required: true, message: "角色名称不能为空", trigger: "blur" }
    ],
    orderId: [{ required: true, message: "排序号不能为空", trigger: "blur" }],
    roleTypeName: [
      { required: true, message: "角色类别不能为空", trigger: "blur" }
    ]
  },
  dialogVisible: false
});

const show = row => {
  if (row) {
    state.dialogTitle = `修改${props.title}`;
    state.formData.id = row.id;
    state.formData.roleCode = row.roleCode;
    state.formData.roleName = row.roleName;
    state.formData.orderId = row.orderId;
    state.formData.roleTypeCode = row.roleTypeCode;
    state.formData.roleTypeName = row.roleTypeName;
    state.formData.remark = row.remark;
  } else {
    state.operationAdd = true;
    state.dialogTitle = `新增${props.title}`;
  }
  state.dialogVisible = true;
};

const close = () => {
  state.operationAdd = false;
  state.dialogTitle = props.title;
  state.formData = {
    id: "",
    roleCode: "",
    roleName: "",
    orderId: 0,
    roleTypeCode: "",
    roleTypeName: "",
    remark: ""
  };
  state.dialogVisible = false;
};

const save = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let data;
      if (state.operationAdd) {
        data = await addRole(state.formData);
      } else {
        data = await updateRole(state.formData);
      }
      if (data.code && data.code === 200) {
        useMessage().success(data.msg);
        emits("confirm", {});
        close();
      } else {
        useMessage().warning(data.msg);
      }
    }
  });
};

const handleRoleNameChange = () => {
  const roleCode = pinyin.getCamelChars(state.formData.roleName).toUpperCase();
  state.formData.roleCode = `ROLE_${roleCode}`;
};

const openRoleTypeSelector = () => {
  const row = {};
  row.treeCode = "role";
  roleTypeRef.value.show(row);
};

const handleRoleTypeSelect = node => {
  state.formData.roleTypeCode = node.nodeCode;
  state.formData.roleTypeName = node.text;
};

defineExpose({
  show,
  close,
  save
});
</script>

<style lang="scss" scoped>
.el-input__inner {
  width: 140px;
}
</style>
